import time
from typing import Dict

import jwt

"""
    所有api 父类
"""


class Base:
    @staticmethod
    def jwt_encode(cls, data, expire=86000):
        """
        jwt 加密
        :param data: 加密数据
        :param expire: token 有效时长
        :return:
        """
        res = {
            'exp': int(time.time()) + expire,
            'iat': int(time.time()),
            'data': data
        }
        res['token'] = jwt.encode(res, 'djcore', algorithm="HS256")
        return res

    @classmethod
    def jwt_decode(cls, data):

        """
        jwt 解码
        :param data: 加密参数
        :return: 解码数据
        """
        try:
            res = jwt.decode(data, 'djcore', algorithms='HS256')
        except jwt.ExpiredSignatureError:
            return cls.api_ajax_error("", "token 过期！")
        except jwt.DecodeError:
            return cls.api_ajax_error("", "token 无效1！")
        except Exception:
            return cls.api_ajax_error("", "token 无效2！")
        return cls.api_ajax_success(res.get('data'))

    @classmethod
    def api_ajax(cls, data: Dict):
        """
        :param data:
        """
        return data

    @classmethod
    def api_ajax_success(cls, data, msg="success"):
        """
        :param data:
        :param msg:
        :return:
        """
        if type(data) == dict:
            return {"err_code": 0, "err_msg": msg, "data": data}
        else:
            return {"err_code": 0, "err_msg": msg, "data": {}}

    @classmethod
    def api_ajax_error(cls, data, msg, code=1):
        """
        :param data:
        :param msg:
        :param code:
        :return:
        """
        if type(data) == dict:
            return {"err_code": code, "err_msg": msg, "data": data}
        else:
            return {"err_code": code, "err_msg": msg, "data": {}}
